<template>
  <div class="flow-user-sign">
    <VueSignaturePad width="925px" height="364px" class="flow-user-sign-comp"
                     ref="signaturePad" :options="signaturePadOptions"/>
    <div class="flow-user-sign-buetton-wrapper">
      <Button type="primary" @click="getCurrentUserSign">调用系统签名</Button>
      <Button @click="clear">清空</Button>
      <Button @click="clear" :disabled="loading">上传</Button>
      <Button @click="undoSignature" :disabled="loading">撤销</Button>
    </div>
  </div>
</template>
<script>
import {VueSignaturePad} from 'vue-signature-pad';
import {Button, notification} from 'ant-design-vue';
import {createModelProps, createProps} from '@/utils';
import {createService} from '@/request/service';

export default {
  name: 'FlowUserSign',
  components: {
    Button,
    VueSignaturePad
  },
  model: createModelProps(),
  props: {
    request: createProps(Object, () => ({
      baseURL: '/h-flow',
      headers: {},
    })),
    value: createProps(String),
  },
  data() {
    return {
      loading: false,
      signaturePadOptions: {
        penColor: '#000',
        minWidth: 1,
        maxWidth: 5,
        onEnd: () => this.change(),
      },
    };
  },
  methods: {
    change() {
      let {isEmpty, data: userSign} = this.$refs.signaturePad.saveSignature();
      if (isEmpty) {
        userSign = undefined;
      }
      this.$emit('change', userSign);
    },
    getCurrentUserSign() {
      createService(this.request).get('/flow/user/getCurrentUserSign', {}).then(userSignURL => {
        if (userSignURL) {
          this.$emit('change', userSignURL);
        } else {
          notification.warn({message: '您当前没有配置手签, 请联系管理员配置手签'});
        }
      });
    },
    undoSignature() {
      this.$refs.signaturePad.undoSignature();
      this.change();
    },
    clear() {
      this.$refs.signaturePad.clearSignature();
      this.$emit('change', undefined);
    },
  },
  watch: {
    value: {
      handler() {
        if (this.value) {
          this.$refs.signaturePad && (
             this.$refs.signaturePad.fromDataURL(this.value)
          );
        }
      },
      immediate: true,
    },
  }
};
</script>
<style>
.flow-user-sign .flow-user-sign-comp {
  border: 1px solid #c9d8db;
}

.flow-user-sign {
}

.flow-user-sign-button-wrapper button {
  margin-right: 5px;
}

.flow-user-sign-button-wrapper {
  padding: 5px 5px 5px 0;
}
</style>